package comment.until;
import comment.model.pojo.Video;

import java.lang.reflect.Field;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class JdbcTemplate {


    public static  int executeDML(String sql, Object... agrs) {
        Connection con = null;
        PreparedStatement pst = null;
        int count = 0;
        try {
            con = JdbcUntil.getConnection();
            pst = con.prepareStatement(sql);
            if (agrs.length > 0 || agrs != null) {
                for (int i = 0; i < agrs.length; i++) {
                    pst.setObject(i + 1, agrs[i]);
                }
            }
            count = pst.executeUpdate();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            JdbcUntil.close(con, pst);
        }
        return count;
    }

    public static<T>  List<T> executeDQL(Class<?> c,String sql, Object... agrs ) throws IllegalAccessException, InstantiationException {
        Connection con = null;
        PreparedStatement pst = null;
        ResultSet rs=null;
        List<T> list=new ArrayList<>();
        ResultSetMetaData rsmd=null;
        Field[] fields=c.getDeclaredFields();



        try {
            con = JdbcUntil.getConnection();
            pst = con.prepareStatement(sql);
            if (agrs.length > 0 || agrs != null) {
                for (int i = 0; i < agrs.length; i++) {
                    pst.setObject(i +1, agrs[i]);
                }
            }
            rs=pst.executeQuery();
            rsmd=pst.getMetaData();
            int count =rsmd.getColumnCount();
            while (rs.next())
            {
                T t=(T)c.newInstance();
                for (int i = 0; i < count; i++) {
                    fields[i].setAccessible(true);
                    fields[i].set(t,rs.getObject(i+1));
                }
                list.add(t);
            }

        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            JdbcUntil.close(con, pst);
        }
        return list;
    }

}